import { View, Text, Picker, ScrollView, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import * as dayjs from 'dayjs'
import { useMemoizedFn, useRequest, useSetState, useInfiniteScroll, } from 'ahooks'
import { getOrderList, getStatsInfo, getWexinConfig, wxjs_cfgs, fetchNbMoney } from '@/api'
import PayLevelConfin from '@/components/PayLevelConfin'

import nodata from '@/static/nodata.png'
import './index.module.scss'

export default function Index() {
  const [params, setParams] = useSetState({
    startTime: dayjs().format('YYYY-MM-DD'),
    endTime: dayjs().format('YYYY-MM-DD'),
  })
// console.log(WeixinJSBridge,'WeixinJSBridge');
  const { data: { data: { earn = [], orders = [], can_nbrmb = false } = {} } = {} } = useRequest(getStatsInfo, {
    onSuccess: (res) => {
      // if (res?.data?.is_vip) {
        Taro.setNavigationBarTitle({
          title: res?.data?.nav_title || '首页'//'VIP 代理商'
        })
      // }
    }
  })
  const { data: { data: { is_sub = false, url = '', tip = '' } = {} } = {} } = useRequest(getWexinConfig)

  // useRequest(wxjs_cfgs({ url: location.href }), { onSuccess: (res) => {
  //   console.log(res);
  // } });

  const {
    data: { total = 0, list: dataList = [] } = {},
    loading: initLoading,
    loadMore,
  } = useInfiniteScroll((d) => {
    const page = d ? Math.ceil(d.list.length / 15) + 1 : 1;
    console.log(222);
    return getOrderList({
      dates: `${params?.startTime},${params?.endTime}`,
      size: 15,
      page
    }).then(res => ({ list: res?.data || [], total: res?.total || 0 }))
  }, {
    isNoMore: (res) => res?.list?.length >= res?.total || false,
    reloadDeps: [params],
    onSuccess(res) {
      console.log(res)

    }
  })

  const setListTime = useMemoizedFn((time) => {
    setParams({
      ...time,
    })
  })

  const handlePreview = useMemoizedFn(() => {
    Taro.previewImage({
      current: url,
      urls: [url]
    })
  })

  const { run } = useRequest(fetchNbMoney, {
    manual: true,
    onSuccess: () => {
      Taro.showToast({ title: '领取成功，请到个人中心提现', icon: 'success' })
    },
  })

  const getNewbieRmb = async () => {
    run()
  }

  return (
    <View className='index-box'>
      <View className='padding top-box'>
        <View className='flex margin-bottom justify-between'>
          {earn?.map(item => (
            <View className='padding-xs flex-sub' key={item?.label}>
              <View className='earn-item radius'>
                <View className='text-sm margin-bottom-xs text-center'>{item?.label}{item?.unit ? `(${item?.unit})` : ''}</View>
                <View className='text-xxl text-center'>{item?.value}</View>
              </View>
            </View>
          ))}
        </View>
        <View className='flex justify-between'>
          {orders?.map(item => (
            <View className='padding-xs flex-sub' key={item?.label}>
              <View className='earn-item radius'>
                <View className='text-sm margin-bottom-xs text-center'>{item?.label}(元)</View>
                <View className='text-xxl text-center'>{item?.value}</View>
              </View>
            </View>
          ))}
        </View>
      </View>
      <View className='flex justify-around padding bg-white'>
        <Picker mode='date' end={dayjs().format('YYYY-MM-DD')} value={params.startTime} onChange={e => setListTime({ startTime: e?.detail?.value })}>
          <View className='picker text-df'>
            开始时间：{params.startTime}<Text className='lg text-gray cuIcon-unfold'></Text>
          </View>
        </Picker>
        <Picker mode='date' end={dayjs().format('YYYY-MM-DD')} value={params.endTime} onChange={e => setListTime({ endTime: e?.detail?.value })}>
          <View className='picker text-df'>
            结束时间：{params.endTime}<Text className='lg text-gray cuIcon-unfold'></Text>
          </View>
        </Picker>
      </View>
      { can_nbrmb && (<View className='nbrmb-btn' onClick={getNewbieRmb}>点击领取刷卡笔数费</View>)}
      <View className='list-box'>
        {
          total === 0 && !initLoading ? (
            <View className='flex-direction flex-center' style={{ "height": '75vh' }}>
              <Image style={{ width: '100rpx' }} mode='widthFix' src={nodata}></Image>
              <View className='text-ds text-99 margin-top-sm'>暂无数据</View>
            </View>
          ) : (
             <ScrollView
               className='scrollview'
               scrollY
               scrollWithAnimation
                // scrollTop={0}
               style={{
                  height: '70vh'
                }}
               lowerThreshold={20}
               onScrollToLower={loadMore}
             >
              {dataList?.map?.((item, index) => (
                <View key={item?.id} className={`flex padding-sm ${index % 2 === 1 ? 'bg-white' : 'bg-gray'}`}>
                  <View className='flex-sub'>
                    <View className='margin-bottom-xs text-df'>交易金额：<Text className='text-red text-dl'>{item?.money}元</Text></View>
                    <View className='text-sm text-66'>交易时间：{item?.order_time}</View>
                  </View>
                  <View className='flex-center text-gl main-color'>
                    {item?.earn}{item?.unit ? `${item?.unit}` : ''}
                  </View>
                </View>
              ))}
                <View className={`cu-load ${dataList?.length >= total ? 'over' : 'loading'}`}></View>
            </ScrollView>
          )
        }
      </View>
      {url && !is_sub && (
        <View onClick={handlePreview} className='flex align-center line-white justify-between guanzhu padding-sm w-100'>
          <Text>{tip || '关注公众号，获取最新消息提醒'}</Text>
          <Text className='main-bc padding-tb-xs padding-lr round'>关注</Text>
        </View>
      )}
      <PayLevelConfin defaultShow />
    </View>
  )
}
